import Config from '../utils/Config.js';
import TopBar from '../components/TopBar.js';
import BattleArea from '../components/BattleArea.js';
import FunctionArea from '../components/FunctionArea.js';
import GameBoard from '../components/GameBoard.js';

/**
 * UI管理器
 * 负责管理所有UI组件的创建、布局和交互
 */
export default class UIManager {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.components = {};
        this.isInitialized = false;
    }

    /**
     * 初始化UI管理器
     */
    init() {
        console.log('UI管理器初始化...');
        
        // 创建或获取canvas
        this.setupCanvas();
        
        // 创建UI组件
        this.createComponents();
        
        // 设置布局
        this.setupLayout();
        
        // 绑定事件
        this.bindEvents();
        
        this.isInitialized = true;
        console.log('UI管理器初始化完成');
    }

    /**
     * 设置游戏管理器引用
     */
    setGameManager(gameManager) {
        this.gameManager = gameManager;
        // 将游戏管理器传递给需要的组件
        Object.values(this.components).forEach(component => {
            if (component.setGameManager) {
                component.setGameManager(gameManager);
            }
        });
    }

    /**
     * 设置适配管理器引用
     */
    setAdaptManager(adaptManager) {
        this.adaptManager = adaptManager;
        // 从适配管理器获取已配置好的Canvas
        this.canvas = adaptManager.getCanvas();
        this.ctx = adaptManager.getContext();
        console.log('UI管理器已连接到适配管理器');
    }

    /**
     * 设置canvas（现在由适配管理器处理）
     */
    setupCanvas() {
        // Canvas设置现在由AdaptManager处理
        if (!this.canvas || !this.ctx) {
            console.warn('Canvas未通过适配管理器设置，使用默认设置');
            this.canvas = wx.createCanvas();
            this.ctx = this.canvas.getContext('2d');
            this.canvas.width = Config.GAME.WIDTH;
            this.canvas.height = Config.GAME.HEIGHT;
        }
        console.log(`UI管理器Canvas就绪: ${this.canvas.width}x${this.canvas.height}`);
    }

    /**
     * 创建UI组件
     */
    createComponents() {
        console.log('创建UI组件...');
        
        // 创建各个组件
        this.components.topBar = new TopBar(this);
        this.components.battleArea = new BattleArea(this);
        this.components.functionArea = new FunctionArea(this);
        this.components.gameBoard = new GameBoard(this);
        
        console.log('UI组件创建完成');
    }

    /**
     * 设置布局
     */
    setupLayout() {
        console.log('设置布局...');
        
        const { WIDTH, HEIGHT } = Config.GAME;
        const { TOP_BAR, LEFT_PANEL, RIGHT_PANEL } = Config.LAYOUT;
        
        // 计算各区域位置和尺寸（左：备战区，中：游戏区，右：功能区）
        const layouts = {
            topBar: {
                x: 0,
                y: 0,
                width: WIDTH,
                height: TOP_BAR.HEIGHT
            },
            
            battleArea: {
                x: 0,
                y: TOP_BAR.HEIGHT,
                width: LEFT_PANEL.WIDTH,
                height: HEIGHT - TOP_BAR.HEIGHT
            },
            
            functionArea: {
                x: WIDTH - RIGHT_PANEL.WIDTH,
                y: TOP_BAR.HEIGHT,
                width: RIGHT_PANEL.WIDTH,
                height: HEIGHT - TOP_BAR.HEIGHT
            },
            
            gameBoard: {
                x: LEFT_PANEL.WIDTH,
                y: TOP_BAR.HEIGHT,
                width: WIDTH - LEFT_PANEL.WIDTH - RIGHT_PANEL.WIDTH,
                height: HEIGHT - TOP_BAR.HEIGHT
            }
        };
        
        // 应用布局到各组件
        Object.keys(layouts).forEach(key => {
            if (this.components[key]) {
                this.components[key].setLayout(layouts[key]);
            }
        });
        
        console.log('布局设置完成');
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 触摸事件处理
        wx.onTouchStart(this.handleTouchStart.bind(this));
        wx.onTouchMove(this.handleTouchMove.bind(this));
        wx.onTouchEnd(this.handleTouchEnd.bind(this));
    }

    /**
     * 处理触摸开始事件
     */
    handleTouchStart(e) {
        const touch = e.touches[0];
        let { clientX, clientY } = touch;

        // 如果有适配管理器，进行坐标转换
        if (this.adaptManager) {
            const gameCoords = this.adaptManager.screenToGameFixed(clientX, clientY);
            clientX = gameCoords.x;
            clientY = gameCoords.y;
        }

        // 将转换后的坐标传递给相应的组件
        // 顺序：备战区 -> 功能区 -> 游戏区 -> 顶部栏
        const componentOrder = ['battleArea', 'functionArea', 'gameBoard', 'topBar'];

        for (const componentName of componentOrder) {
            const component = this.components[componentName];

            if (component && component.isPointInside && component.isPointInside(clientX, clientY)) {
                const handled = component.onTouchStart && component.onTouchStart(clientX, clientY);
                if (handled === true) {
                    break; // 已处理则停止，否则继续尝试下一个组件
                }
            }
        }
    }

    /**
     * 处理触摸移动事件
     */
    handleTouchMove(e) {
        const touch = e.touches[0];
        let { clientX, clientY } = touch;
        
        // 如果有适配管理器，进行坐标转换
        if (this.adaptManager) {
            const gameCoords = this.adaptManager.screenToGame(clientX, clientY);
            clientX = gameCoords.x;
            clientY = gameCoords.y;
        }
        
        Object.values(this.components).forEach(component => {
            component.onTouchMove && component.onTouchMove(clientX, clientY);
        });
    }

    /**
     * 处理触摸结束事件
     */
    handleTouchEnd(e) {
        Object.values(this.components).forEach(component => {
            component.onTouchEnd && component.onTouchEnd();
        });
    }

    /**
     * 渲染所有UI组件
     */
    render() {
        if (!this.isInitialized) return;
        
        // 清空画布
        this.ctx.clearRect(0, 0, Config.GAME.WIDTH, Config.GAME.HEIGHT);
        
        // 绘制背景
        this.drawBackground();
        
        // 渲染各个组件
        Object.values(this.components).forEach(component => {
            component.render && component.render(this.ctx);
        });
    }

    /**
     * 绘制背景
     */
    drawBackground() {
        // 尝试加载背景图片
        if (!this.backgroundImage) {
            this.loadBackgroundImage();
        }
        
        if (this.backgroundImage && this.backgroundImage.complete) {
            // 绘制背景图片，拉伸到整个画布
            this.ctx.drawImage(
                this.backgroundImage, 
                0, 0, 
                Config.GAME.WIDTH, 
                Config.GAME.HEIGHT
            );
        } else {
            // 如果图片未加载，使用纯色背景
            this.ctx.fillStyle = Config.COLORS.BACKGROUND;
            this.ctx.fillRect(0, 0, Config.GAME.WIDTH, Config.GAME.HEIGHT);
        }
    }

    /**
     * 加载背景图片
     */
    loadBackgroundImage() {
        if (this.backgroundImage) return;
        
        this.backgroundImage = wx.createImage();
        this.backgroundImage.onload = () => {
            console.log('背景图片加载完成');
        };
        this.backgroundImage.onerror = () => {
            console.log('背景图片加载失败，使用纯色背景');
        };
        this.backgroundImage.src = 'images/image_bg.png';
    }

    /**
     * 获取组件
     */
    getComponent(name) {
        return this.components[name];
    }
}
